﻿using DKPScoreWebApi.DTOs.Requests;
using DKPScoreWebApi.DTOs.Results;
using DKPScoreWebApi.Models;
using DKPScoreWebApi.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace DKPScoreWebApi.Controllers
{
    [ApiController]
    [Route("api/guilds/{guildId}/points")]
    public class PointsController : ControllerBase
    {
        private readonly IDkpService _dkpService;
        private readonly IGuildService _guildService;
        private readonly ILogger<PointsController> _logger;

        public PointsController(IDkpService dkpService, IGuildService guildService, ILogger<PointsController> logger)
        {
            _dkpService = dkpService;
            _guildService = guildService;
            _logger = logger;
        }

        [HttpPost("add")]
        public async Task<ActionResult<ApiResult<PointResult>>> AddPoints(int userId, int guildId, [FromBody] AddPointsRequest request)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                var result = await _dkpService.AddPointsAsync(userId, guildId, request);
                if (!result.Success)
                    return BadRequest(new ApiResult { Success = false, Message = result.Message });

                return Ok(new ApiResult<PointResult> { Success = true, Data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加积分失败");
                return BadRequest(new ApiResult { Success = false, Message = "添加积分失败" });
            }
        }

        [HttpPost("progress")]
        public async Task<ActionResult<ApiResult<ProgressResult>>> UpdateProgress(int userId, int guildId, [FromBody] UpdateProgressRequest request)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                var result = await _dkpService.UpdateProgressAsync(userId, guildId, request);
                if (!result.Success)
                    return BadRequest(new ApiResult { Success = false, Message = result.Message });

                return Ok(new ApiResult<ProgressResult> { Success = true, Data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新进度失败");
                return BadRequest(new ApiResult { Success = false, Message = "更新进度失败" });
            }
        }

        [HttpGet("records")]
        public async Task<ActionResult<ApiResult<List<PointRecord>>>> GetRecords(int userId, int guildId,
            [FromQuery] DateTime? startDate = null, [FromQuery] DateTime? endDate = null, [FromQuery] int? memberId = null)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                var records = await _dkpService.GetGuildRecordsAsync(guildId, startDate, endDate, memberId);
                return Ok(new ApiResult<List<PointRecord>> { Success = true, Data = records });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取积分记录失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取记录失败" });
            }
        }

        [HttpGet("ranking")]
        public async Task<ActionResult<ApiResult<List<GuildMember>>>> GetRanking(int userId, int guildId, [FromQuery] int topCount = 50)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                var ranking = await _dkpService.GetGuildRankingAsync(guildId, topCount);
                return Ok(new ApiResult<List<GuildMember>> { Success = true, Data = ranking });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取排名失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取排名失败" });
            }
        }

        [HttpGet("members/{memberId}/records")]
        public async Task<ActionResult<ApiResult<List<PointRecord>>>> GetMemberRecords(int userId, int guildId, int memberId,
            [FromQuery] DateTime? startDate = null, [FromQuery] DateTime? endDate = null)
        {
            try
            {
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                var records = await _dkpService.GetMemberRecordsAsync(guildId, memberId, startDate, endDate);
                return Ok(new ApiResult<List<PointRecord>> { Success = true, Data = records });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取成员记录失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取记录失败" });
            }
        }
    }
}
